#ifndef _MUTEX_HPP_
#define _MUTEX_HPP_

#include <pthread.h>

namespace MutexModule
{
    class Mutex
    {
    public:
        Mutex(const Mutex &) = delete;// 禁用拷贝构造函数
        const Mutex &operator=(const Mutex &) = delete;// 禁用拷贝赋值运算符
        Mutex()
        {
            pthread_mutex_init(&_mutex, nullptr);
        }
        ~Mutex()
        {
            pthread_mutex_destroy(&_mutex);
        }
        bool lock()
        {
            return pthread_mutex_lock(&_mutex) == 0;
        }
        bool unlock()
        {
            return pthread_mutex_unlock(&_mutex) == 0;
        }
        pthread_mutex_t *LockPtr()
        {
            return &_mutex;
        }

    private:
        pthread_mutex_t _mutex; // 互斥量锁
    };

    class LockGuard // 采⽤RAII⻛格，进⾏锁管理
    {
    public:
        LockGuard(Mutex &mtx) : _mtx(mtx) // 通过后续使用时定义一个LockGuard类型的局部变量，在局部变量的声明周期内，互斥量会被自动加锁与解锁
        {
            _mtx.lock();
        }
        ~LockGuard()
        {
            _mtx.unlock();
        }

    private:
        Mutex &_mtx;
    };
}

#endif